﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;

namespace UDMBackService
{
    public class HttpService
    {
        private const int Port = 54321;
        private string BaseUrl = "http://127.0.0.1:" + Port;

        public async Task StartAsync()
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add($"{BaseUrl}/");
            listener.Start();
            Console.WriteLine($"服务已启动，监听地址：{BaseUrl}");

            while (true)
            {
                HttpListenerContext context = await listener.GetContextAsync();
                HandleRequest(context);
            }
        }
        private static void HandleRequest(HttpListenerContext ctx)
        {
            var req = ctx.Request;
            var resp = ctx.Response;
            HttpClient http = new HttpClient();
            ResponseModel responseModel;
            string ver = Assembly.GetExecutingAssembly().GetName().Version.ToString(); ;
            bool flag = true;
            string path = "";
            string result = "success";

            try
            {
                // 1. 统一加上 CORS 头（* 仅本地调试用）
                ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                ctx.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, proversion");
                ctx.Response.AddHeader("Access-Control-Allow-Credentials", "true");

                // 2. 处理 OPTIONS 预检请求
                if (ctx.Request.HttpMethod == "OPTIONS")
                {
                    ctx.Response.StatusCode = 200;
                    ctx.Response.Close();
                    return;
                }

                // ===== 2. /ver 路由 =====
                if (req.Url.AbsolutePath.Equals("/ver", StringComparison.OrdinalIgnoreCase))
                {
                    string json = $"{{\"ver\":\"{ver}\"}}";
                    byte[] buff = Encoding.UTF8.GetBytes(json);
                    resp.ContentType = "application/json; charset=utf-8";
                    resp.ContentLength64 = buff.Length;
                    resp.OutputStream.Write(buff, 0, buff.Length);
                    resp.Close();
                    return;   // 处理完直接返回
                }

                // 只认 POST + multipart
                if (!req.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) ||
                    !req.ContentType.StartsWith("multipart/form-data", StringComparison.OrdinalIgnoreCase))
                {
                    resp.StatusCode = 404;
                    resp.Close();
                    return;
                }

                /* 1. 解析 multipart */
                var parser = new MultipartParser();
                parser.Parse(req);

                var changetype = parser.Parameters.ContainsKey("changetype")? parser.Parameters["changetype"]: "";
                var notifyUrl = parser.Parameters.ContainsKey("url") ? parser.Parameters["url"] : "";
                var token = parser.Parameters.ContainsKey("token") ? parser.Parameters["token"] : "";
                var sheetName = parser.Parameters.ContainsKey("sheetname") ? parser.Parameters["sheetname"] : "";
                var excelPart = parser.Files.FirstOrDefault();

                if (excelPart == null || string.IsNullOrEmpty(notifyUrl))
                {
                    resp.StatusCode = 400;
                    resp.Close();
                    return;
                }

                /* 2. 临时 Excel */
                var tempXls = Path.Combine(Path.GetTempPath(), excelPart.FileName);
                File.WriteAllBytes(tempXls, excelPart.Data);

                /* 3. 转换 PDF（你的逻辑） */
                var tempPdf = Path.ChangeExtension(tempXls, ".pdf");
                //ExcelToPdf(tempXls, tempPdf, sheetName); // 替换成真实方法

                if (File.Exists(tempXls))
                {
                    if (changetype.ToLower().Equals("pdf"))
                    {
                        string ext = Path.GetExtension(tempXls).TrimStart('.').ToUpperInvariant();

                        if (ext.Equals("DOC") || ext.Equals("DOCX"))
                        {
                            if (string.IsNullOrEmpty(changetype) || string.IsNullOrEmpty(tempXls))
                            {
                                responseModel = new ResponseModel
                                {
                                    Status = "fail",
                                    Ver = ver,
                                    Result = @"调用的参数不正确，请核实。"
                                };
                                flag = false;
                                //return;
                            }
                            else
                            {
                                path = ChangeWordToPDF(tempXls, ref result);
                                responseModel = new ResponseModel
                                {
                                    Status = result,
                                    Ver = ver,
                                    Result = "PDF转换成功"
                                };
                            }
                        }
                        else if (ext.Equals("XLSX") || ext.Equals("XLS"))
                        {
                            if (string.IsNullOrEmpty(changetype) || string.IsNullOrEmpty(tempXls) ||
                                string.IsNullOrEmpty(sheetName))
                            {
                                responseModel = new ResponseModel
                                {
                                    Status = "fail",
                                    Ver = ver,
                                    Result = @"调用的参数不正确，请核实。"
                                };
                                flag = false;
                            }
                            else
                            {
                                path = ChangeExcelToPDF(tempXls, sheetName, ref result);
                                responseModel = new ResponseModel
                                {
                                    Status = result,
                                    Ver = ver,
                                    Result = "PDF转换成功"
                                };
                            }
                        }
                        else
                        {
                            responseModel = new ResponseModel
                            {
                                Status = "fail",
                                Ver = ver,
                                Result = "只能把类型为Excel、Word文件转换为PDF文件！"
                            };
                        }
                    }
                    else
                    {
                        responseModel = new ResponseModel
                        {
                            Status = "fail",
                            Ver = ver,
                            Result = "changetype的参数不正确，只能是以下的范围：【pdf】!"
                        };
                    }
                }
                else
                {
                    // 构建响应
                    responseModel = new ResponseModel
                    {
                        Status = "fail",
                        Ver = ver,
                        Result = "要转换的文件【" + excelPart.FileName + "】不存在！"
                    };
                }

                try
                {
                    /* 4. 回传 PDF 到 Web 给的 url，带 token */
                    var multipart = new MultipartFormDataContent();
                    var content = new ByteArrayContent(File.ReadAllBytes(path));
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                    multipart.Add(content, "files", Path.GetFileName(path));

                    http.DefaultRequestHeaders.Clear();
                    http.DefaultRequestHeaders.Add("Authorization", token);
                    http.DefaultRequestHeaders.Add("prdVersion", "100.100.2999.12.31");
                    //var pushResp = http.PostAsync(notifyUrl, content).Result;
                    var pushResp = http.PostAsync(notifyUrl, multipart).Result;

                    /* 5. 把下游回执原样返给 Java 客户端 */
                    var body = pushResp.Content.ReadAsStringAsync().Result;
                    resp.StatusCode = (int)pushResp.StatusCode;
                    resp.ContentType = "application/json; charset=utf-8";
                    var buf = Encoding.UTF8.GetBytes(body);
                    resp.ContentLength64 = buf.Length;
                    resp.OutputStream.Write(buf, 0, buf.Length);
                }
                catch (Exception ex)
                {
                    responseModel = new ResponseModel
                    {
                        Status = "fail",
                        Ver = ver,
                        Result = "错误信息：" + ex.Message
                    };
                    string jsonResponse = JsonConvert.SerializeObject(responseModel);
                    byte[] buffer = Encoding.UTF8.GetBytes(jsonResponse);

                    ctx.Response.ContentType = "application/json";
                    ctx.Response.ContentLength64 = buffer.Length;
                    ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    ctx.Response.Close();
                }
                
                /* 6. 清理 */
                File.Delete(tempXls);
                File.Delete(tempPdf);
            }
            catch (Exception e)
            {
                resp.StatusCode = 500;
                var buf = Encoding.UTF8.GetBytes(e.Message);
                resp.ContentLength64 = buf.Length;
                resp.OutputStream.Write(buf, 0, buf.Length);
            }
            finally
            {
                resp.Close();
            }
        }
        private void HandleRequest1(HttpListenerContext context)
        {
            string path = "";
            ResponseModel responseModel;
            string ver;
            bool flag = true;
            ver = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            string result = "success";
            string param2 = "";

            try
            {
                // 1. 统一加上 CORS 头（* 仅本地调试用）
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, proversion");
                context.Response.AddHeader("Access-Control-Allow-Credentials", "true");

                // 2. 处理 OPTIONS 预检请求
                if (context.Request.HttpMethod == "OPTIONS")
                {
                    context.Response.StatusCode = 200;
                    context.Response.Close();
                    return;
                }

                //获取上传的文件
                if (context.Request.HttpMethod == "POST" && context.Request.ContentType.StartsWith("multipart/form-data"))
                {
                    var parser = new MultipartParser();
                    if (parser.Parse(context.Request))
                    {
                        var file = parser.Files.FirstOrDefault();
                        if (file != null)
                        {
                            param2 = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + "_" + file.FileName);
                            File.WriteAllBytes(param2, file.Data);

                            //responseModel = new ResponseModel
                            //{
                            //    Status = "success",
                            //    Ver = ver,
                            //    UDM = "",
                            //    Result = $"文件已保存到：{tempPath}"
                            //};
                        }
                        else
                        {
                            responseModel = new ResponseModel
                            {
                                Status = "fail",
                                Ver = ver,
                                UDM = "",
                                Result = "未找到上传的文件"
                            };
                            flag = false;
                        }
                    }
                    else
                    {
                        responseModel = new ResponseModel
                        {
                            Status = "fail",
                            Ver = ver,
                            UDM = "",
                            Result = "解析 multipart 数据失败"
                        };
                        flag = false;
                    }
                }
                else
                {
                    responseModel = new ResponseModel
                    {
                        Status = "fail",
                        Ver = ver,
                        Result = "只支持 POST multipart/form-data 上传"
                    };
                    flag = false;
                }

                if (flag)
                {


                }
                // 获取请求参数
                string query = context.Request.Url.Query;
                var queryParams = HttpUtility.ParseQueryString(query);
                //string param1 = queryParams["param1"];
                string param1 = queryParams["changetype"];
                //string param2 = queryParams["param2"];
                //string param2 = queryParams["filepath"];
                string param3 = queryParams["sheetname"];
                string param4 = queryParams["outpath"];

                responseModel = new ResponseModel
                {
                    Status = "success",
                    Ver = ver,
                    Result = ""
                };
                //if (string.IsNullOrEmpty(param1) || string.IsNullOrEmpty(param2) || 
                //    string.IsNullOrEmpty(param3))
                //{
                //    responseModel = new ResponseModel
                //    {
                //        Status = "fail",
                //        Ver = ver,
                //        Result = @"调用的参数不正确，请核实。例：127.0.0.1:54321/?changetype=pdf&filepath=D:\Test\abc.xlsx&sheetname=&outpath=d:\Test"
                //    };
                //    flag = false;
                //    //return;
                //}

                //if (!Directory.Exists(param4))
                //{
                //    responseModel = new ResponseModel
                //    {
                //        Status = "fail",
                //        Ver = ver,
                //        Result = "输出路径【"  + param4 + "】不存在！"
                //    };
                //    flag = false;
                //}
                //if (flag)
                //{
                    if (File.Exists(param2))
                    {
                        if (param1.ToLower().Equals("pdf"))
                        {
                            //if (string.IsNullOrEmpty(param3))
                            //{
                            //    path = ChangeToPDF(param2);
                            //}
                            //else
                            {
                                //path = ChangeExcelToPDF(param2, param3, param4, ref result);
                                string ext = Path.GetExtension(param2).TrimStart('.').ToUpperInvariant();

                                if (ext.Equals("DOC") || ext.Equals("DOCX"))
                                {
                                    if (string.IsNullOrEmpty(param1) || string.IsNullOrEmpty(param2))
                                    {
                                        responseModel = new ResponseModel
                                        {
                                            Status = "fail",
                                            Ver = ver,
                                            Result = @"调用的参数不正确，请核实。例：127.0.0.1:54321/?changetype=pdf&filepath=D:\Test\abc.docx"
                                        };
                                        flag = false;
                                        //return;
                                    }
                                    else
                                    {
                                        path = ChangeWordToPDF(param2, ref result);
                                        responseModel = new ResponseModel
                                        {
                                            Status = result,
                                            Ver = ver,
                                            Result = path
                                        };
                                    }
                                }
                                else if (ext.Equals("XLSX") || ext.Equals("XLS"))
                                {
                                    if (string.IsNullOrEmpty(param1) || string.IsNullOrEmpty(param2) ||
                                        string.IsNullOrEmpty(param3))
                                    {
                                        responseModel = new ResponseModel
                                        {
                                            Status = "fail",
                                            Ver = ver,
                                            Result = @"调用的参数不正确，请核实。例：127.0.0.1:54321/?changetype=pdf&filepath=D:\Test\abc.xlsx&sheetname="
                                        };
                                        flag = false;
                                        //return;
                                    }
                                    else
                                    {
                                        path = ChangeExcelToPDF(param2, param3, ref result);
                                        responseModel = new ResponseModel
                                        {
                                            Status = result,
                                            Ver = ver,
                                            Result = path
                                        };
                                    }
                                }
                                else
                            {
                                responseModel = new ResponseModel
                                {
                                    Status = "fail",
                                    Ver = ver,
                                    Result = "只能把类型为Excel、Word文件转换为PDF文件！"
                                };
                            }
                            }
                            // 处理请求
                            //string result = ProcessRequest(param1, param2);

                            // 构建响应
                            //responseModel = new ResponseModel
                            //{
                            //    Status = result,
                            //    Ver = ver,
                            //    Result = path
                            //};
                        }
                        else
                        {
                            responseModel = new ResponseModel
                            {
                                Status = "fail",
                                Ver = ver,
                                Result = "changetype的参数不正确，只能是以下的范围：【pdf】!"
                            };
                        }
                    }
                    else
                    {
                        // 构建响应
                        responseModel = new ResponseModel
                        {
                            Status = "fail",
                            Ver = ver,
                            Result = "要转换的文件【" + param2 + "】不存在！"
                        };
                    }
                //}
                //string jsonResponse = JsonConvert.SerializeObject(responseModel);
                //byte[] buffer = Encoding.UTF8.GetBytes(jsonResponse);

                //context.Response.ContentType = "application/json";
                //context.Response.ContentLength64 = buffer.Length;
                //context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                //context.Response.Close();
            }
            catch (Exception ex)
            {
                //context.Response.StatusCode = 500;
                //context.Response.Close();
                //Console.WriteLine($"错误：{ex.Message}");
                responseModel = new ResponseModel
                {
                    Status = "fail",
                    Ver = ver,
                    Result = ex.Message
                };
            }

            string jsonResponse = JsonConvert.SerializeObject(responseModel);
            byte[] buffer = Encoding.UTF8.GetBytes(jsonResponse);

            context.Response.ContentType = "application/json";
            context.Response.ContentLength64 = buffer.Length;
            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            context.Response.Close();
        }

        private string ProcessRequest(string param1, string param2)
        {
            // 示例处理逻辑：将两个字符串拼接
            return $"处理结果：{param1} + {param2}";
        }
       
        private static string ChangeToPDF(string file)
        {
            string pdfFilePath = ""; // 替换为你想要保存的PDF文件路径
            string wbName;
            string pdfFolder;
            string sheetName = "";
            Excel.Application application;
            Excel.Workbook workbook = null;
            string tempFolder;

            try
            {
                //pdfFolder = foldPath + @"\pdf";
                //if (!Directory.Exists(pdfFolder))
                //{
                //    Directory.CreateDirectory(pdfFolder);
                //}
                application = new Excel.Application();
                // 打开Excel文件
                workbook = application.Workbooks.Open(file);
                // 获取第一个工作表
                //if (!string.IsNullOrEmpty(tbSheetName.Text.Trim()))
                //{
                //    sheetName = tbSheetName.Text.Trim();
                //}
                //else
                //{
                //    sheetName = ((Excel.Worksheet)workbook.Sheets[1]).Name;
                //}
                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1]; // 索引为1表示第一个工作表
                if (worksheet != null)
                {
                    //遍历行，看是否有行不能完整显示，调整行高
                    //ResizeRowHeight(workbook, worksheet);

                    wbName = workbook.Name.Split('.')[0];

                    tempFolder = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString("N");
                    Directory.CreateDirectory(tempFolder);
                    pdfFilePath = tempFolder + @"\" + wbName + ".pdf";
                    tempFolder = tempFolder + @"\" + "saveAsPDF.xlsx";
                    //workbook.SaveCopyAs(@"D:\testPDF.xlsx");
                    workbook.SaveCopyAs(tempFolder);
                    // 导出为PDF，第一个参数指定转出为PDF，还可以指定为XPS格式
                    worksheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFilePath, Excel.XlFixedFormatQuality.xlQualityStandard, false, false);
                    //report.pdf = pdfFilePath;
                    //report.result = "成功";
                }
                else
                {
                    //report.result = "失败";
                    //report.reason = "未找到名为“" + sheetName + "”的Sheet！";
                }
            }
            catch (Exception ex)
            {
                //report.result = "失败";
                //report.reason = ex.Message;
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(false);
                }
                //ExcelApp.App.ScreenUpdating = true;
            }
            return pdfFilePath;
            //reportList.Add(report);
        }
        private static string ChangeWordToPDF(string file, ref string result)
        {
            string pdfFilePath = ""; // 替换为你想要保存的PDF文件路径
            string pdfFolder;
            //string sheetName = "";
            Word.Application wordApp = null;
            Word.Document doc = null;
            string tempFolder;
            string fileName = Path.GetFileNameWithoutExtension(file);

            try
            {
                result = "success";
                wordApp = new Word.Application();
                // 打开Word文件
                wordApp = new Word.Application
                {
                    Visible = false,               // 后台运行
                    DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
                };

                doc = wordApp.Documents.Open(
                        FileName: file,
                        ConfirmConversions: false,
                        ReadOnly: true,
                        AddToRecentFiles: false);
                tempFolder = System.IO.Path.GetTempPath() + DateTime.Now.ToString("yyyyMMddHHmmssffff");
                Directory.CreateDirectory(tempFolder);
                pdfFilePath = tempFolder + @"\" + fileName + ".pdf";
                // 17 = wdExportFormatPDF  (Word 2007 SP2+ 支持)
                doc.ExportAsFixedFormat(
                        OutputFileName: pdfFilePath,
                        ExportFormat: Word.WdExportFormat.wdExportFormatPDF,
                        OpenAfterExport: false,
                        OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
                        Range: Word.WdExportRange.wdExportAllDocument,
                        Item: Word.WdExportItem.wdExportDocumentContent,
                        IncludeDocProps: true,
                        KeepIRM: true,
                        CreateBookmarks: Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks,
                        DocStructureTags: true,
                        BitmapMissingFonts: true,
                        UseISO19005_1: false);
            }
            catch (Exception ex)
            {
                result = "fail";
                pdfFilePath = ex.Message;
                //report.result = "失败";
                //report.reason = ex.Message;
            }
            finally
            {
                // 释放 COM 对象，否则 WINWORD.EXE 会驻留
                if (doc != null) 
                { 
                    doc.Close(false); 
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(doc); 
                }
                if (wordApp != null) 
                { 
                    wordApp.Quit(false); 
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wordApp); 
                }
            }
            return pdfFilePath;
            //reportList.Add(report);
        }
        private static string ChangeExcelToPDF(string file, string sheetName, ref string result)
        {
            string pdfFilePath = ""; // 替换为你想要保存的PDF文件路径
            string wbName;
            string pdfFolder;
            //string sheetName = "";
            Excel.Application application;
            Excel.Workbook workbook = null;
            string tempFolder;
            Excel.Worksheet worksheet = null;

            try
            {
                result = "success";
                application = new Excel.Application();
                // 打开Excel文件
                workbook = application.Workbooks.Open(file);
                if (IsExistedSheetName(workbook, sheetName))
                {
                    worksheet = (Excel.Worksheet)workbook.Worksheets[sheetName]; // 索引为1表示第一个工作表
                }
                else
                {
                    result = "fail";
                    pdfFilePath = "未找到名为【" + sheetName + "】的Sheet！";
                }
                if (worksheet != null)
                {
                    wbName = workbook.Name.Split('.')[0];

                    tempFolder = System.IO.Path.GetTempPath() + DateTime.Now.ToString("yyyyMMddHHmmssffff"); 
                    Directory.CreateDirectory(tempFolder);
                    pdfFilePath = tempFolder + @"\" + wbName + ".pdf";
                    //tempFolder = tempFolder + @"\" + "saveAsPDF.xlsx";
                    // 导出为PDF，第一个参数指定转出为PDF，还可以指定为XPS格式
                    worksheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFilePath, Excel.XlFixedFormatQuality.xlQualityStandard, false, false);
                    //report.pdf = pdfFilePath;
                    //report.result = "成功";
                }
                else
                {
                    //report.result = "失败";
                    //report.reason = "未找到名为“" + sheetName + "”的Sheet！";
                }
            }
            catch (Exception ex)
            {
                result = "fail";
                pdfFilePath = ex.Message;
                //report.result = "失败";
                //report.reason = ex.Message;
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(false);
                }
                //ExcelApp.App.ScreenUpdating = true;
            }
            return pdfFilePath;
            //reportList.Add(report);
        }
        private static string ChangeToPDF(string file, string sheetName, string outpath, ref string result)
        {
            string pdfFilePath = ""; // 替换为你想要保存的PDF文件路径
            string wbName;
            string pdfFolder;
            //string sheetName = "";
            Excel.Application application;
            Excel.Workbook workbook = null;
            string tempFolder;
            Excel.Worksheet worksheet = null;

            try
            {
                result = "success";
                application = new Excel.Application();
                // 打开Excel文件
                workbook = application.Workbooks.Open(file);
                if (IsExistedSheetName(workbook,sheetName))
                {
                    worksheet = (Excel.Worksheet)workbook.Worksheets[sheetName]; // 索引为1表示第一个工作表
                }
                else
                {
                    result = "fail";
                    pdfFilePath = "未找到名为【" + sheetName + "】的Sheet！";
                }
                if (worksheet != null)
                {
                    wbName = workbook.Name.Split('.')[0];

                    //tempFolder = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString("N");
                    //Directory.CreateDirectory(tempFolder);
                    pdfFilePath = outpath + @"\" + wbName + ".pdf";
                    //tempFolder = tempFolder + @"\" + "saveAsPDF.xlsx";
                    // 导出为PDF，第一个参数指定转出为PDF，还可以指定为XPS格式
                    worksheet.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFilePath, Excel.XlFixedFormatQuality.xlQualityStandard, false, false);
                    //report.pdf = pdfFilePath;
                    //report.result = "成功";
                }
                else
                {
                    //report.result = "失败";
                    //report.reason = "未找到名为“" + sheetName + "”的Sheet！";
                }
            }
            catch (Exception ex)
            {
                result = "fail";
                pdfFilePath = ex.Message;
                //report.result = "失败";
                //report.reason = ex.Message;
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close(false);
                }
                //ExcelApp.App.ScreenUpdating = true;
            }
            return pdfFilePath;
            //reportList.Add(report);
        }
        private static bool IsExistedSheetName(Excel.Workbook wb,string sheetName)
        {
            bool result = false;

            foreach(Excel.Worksheet sn in wb.Sheets)
            {
                if (sn.Name.Equals(sheetName))
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }
    public class ResponseModel
    {
        public string Status { get; set; }
        public string Result { get; set; }
        public string Ver { get; set; }
        public string UDM { get; set; }
    }
    public enum OfficeType
    {
        Unknown,
        Word,
        Excel
    }
}
